const { io } = require('socket.io-client')
import event from './event'
import data from './data'
import { Message } from 'element-ui'
import { resetRouter } from './router'
import { removeToken, getToken } from './utils/auth'
import { serverUrl } from './const'

export default class WebSock {
    static ws = null
    meDisconnect = false

    async connect(url, path = '/socket.io', token) {
      if (WebSock.ws !== null) {
        this.meDisconnect = true
        WebSock.ws.off()
        WebSock.ws.disconnect()
      }

      WebSock.ws = io(url, {
        path,
        query: {},
        transports: ['websocket', 'polling'],
        timeout: 5000,
        reconnectionAttempts: 10,
        auth: { token, platform: "web" }
      })

      WebSock.ws.on('connect', () => {
        console.log('websock connection')
        this.meDisconnect = false
        event.emit('socketConnect')
      })

      WebSock.ws.on('disconnect', () => {
        console.log('disconnect from websocket')
        if (this.meDisconnect) return
        console.log('disconnect')
        console.trace()
      })

      // 刷新架构
      WebSock.ws.on('REFRESH_CONTACT', () => {
        console.log('刷新架构')
        data.contachtList = null
        event.emit('refresh_contact')
      })

      // 新任务
      WebSock.ws.on('TASK-NEW', () => {
        console.log('新任务')
        event.emit('TASK-NEW')
      })

      // 任务变动
      WebSock.ws.on('TASK-CHANGE', () => {
        console.log('任务变动')
        event.emit('TASK-CHANGE')
      })

      // 新通知
      WebSock.ws.on('NOTIFICATION-NEW', () => {
        console.log('新通知')
        event.emit('NOTIFICATION-NEW')
      })

      // 通知变动
      WebSock.ws.on('NOTIFICATION-CHANGE', () => {
        console.log('通知变动')
        event.emit('NOTIFICATION-CHANGE')
      })

      // 重新登录
      WebSock.ws.on('RE-LOGIN', () => {
        this.disconnect()
        Message({ message: '登录凭证过期，请重新登录', type: 'error', duration: 3 * 1000 })
        data.token = ''
        removeToken()
        resetRouter()
      })

      // 账号在其他地方登录
      WebSock.ws.on('DUPLICATE-LOGIN', () => {
        this.disconnect()
        Message({ message: '账号在别处登录', type: 'error', duration: 3 * 1000 })
        data.token = ''
        removeToken()
        resetRouter()
        location.reload()
      })

      // 重连成功
      WebSock.ws.io.on('reconnect', () => {
        this.meDisconnect = false
        console.log('reconnect to websocket success')
      })

      // 正在重连
      WebSock.ws.io.on('reconnect_attempt', () => {
        console.log('attempt reconnect to websocket')
      })

      // 重连失败
      WebSock.ws.io.on('reconnect_failed', () => {
        console.log('reconnect to websocket failed')
        resetRouter()
      })
    }

    // 断开连接
    disconnect() {
      if (WebSock.ws == null) return
      this.meDisconnect = true
      WebSock.ws.off()
      WebSock.ws.disconnect()
      WebSock.ws = null
    }

    // 进行请求
    async performRequest(route, params = {}) {
      console.log('perform request', route, params, data)
      const token = getToken();
      console.log(token);
      if (!token) return resetRouter()
      if (WebSock.ws == null) {
        // serverUrl
        websock.connect('wss://' + serverUrl, '/socket-io', token)
      }
      return new Promise((resolve, reject) => {
        WebSock.ws.emit(route, params, res => {
          if (res.code === 9999) {
            data.token = ''
            removeToken()
            Message({ message: '请重新登录', type: 'error', duration: 3 * 1000 })
            return resetRouter()
          }

          console.log('perform request222', res)
          if (res.code !== 0) {
            Message({ message: res.message, type: 'error', duration: 3 * 1000 })
            return reject(new Error(res.message))
          }
          console.log(res.data, 'res.datares.datares.data')
          if (res.data != undefined || res.data != null) {
            resolve(res.data);
          } else {
            resolve(res);
          }
        })
      })
    }

    // ping
    async ping() {
      return await this.performRequest('ping')
    }

    // 获取信息
    async getUserInfo() {
      console.log('get user info', data)
      if (data.userInfo) return data.userInfo
      try {
        const res = await this.performRequest('userInfo')
        console.log('get user info res', res)
        data.userInfo = res
        return res
      } catch (e) {
        throw e.message
      }
    }

    // 修改昵称
    modifyName(token, name, ack) {
      if (WebSock.ws == null) return resetRouter()
      WebSock.ws.emit('modifyName', { token, name }, ack)
    }

    // 获取联系人列表
    async getContactList() {
      return this.performRequest('contactList')
    }

    // 获取用户列表
    async userList(params) {
      return this.performRequest('userList', params)
    }

    // 添加用户
    async addUser(params) {
      return this.performRequest('addUser', params)
    }

    // 添加用户岗位
    async addUserDp(params) {
      return this.performRequest('addUserDp', params)
    }

    // 删除用户岗位
    async rmUserDp(params) {
      return this.performRequest('rmUserDp', params)
    }

    // 更新用户岗位
    async updateUserDp(params) {
      return this.performRequest('updateUserDp', params)
    }

    // 用户离职
    async userLizhi(params) {
      return this.performRequest('userLizhi', params)
    }

    // 用户转正
    async userZhuanzheng(params) {
      return this.performRequest('userZhuanzheng', params)
    }

    // 修改密码
    async modifyPwd(params) {
      return this.performRequest('modifyPwd', params)
    }

    // 修改用户信息
    async modifyUserInfo(params) {
      return this.performRequest('modifyUserInfo', params)
    }

    // 获取部门列表
    async getDepartList() {
      return this.performRequest('departList')
    }

    async modifyZhijieLingdao(params) {
      return this.performRequest('modifyZhijieLingdao', params)
    }
    async modifyFenguanLingdao(params) {
      return this.performRequest('modifyFenguanLingdao', params)
    }
    async modifyZhuyaoLingdao(params) {
      return this.performRequest('modifyZhuyaoLingdao', params)
    }

    // 查看部门人员
    async departMembers(params) {
      return this.performRequest('departMembers', params)
    }

    async setDepartLingdao(params) {
      return this.performRequest('setDepartLingdao', params)
    }

    // 添加部门
    async addDepart(params) {
      data.departList = null
      return this.performRequest('addDepart', params)
    }

    // 删除部门
    async delDepart(params) {
      data.departList = null
      return this.performRequest('delDepart', params)
    }

    // 查看岗位人员
    async posMembers(params) {
      return this.performRequest('posMembers', params)
    }
    // 添加岗位
    async addPos(params) {
      data.posList = null
      return this.performRequest('addPos', params)
    }
    async modifyPosName(params) {
      data.posList = null
      return this.performRequest('modifyPosName', params)
    }
    // 删除岗位
    async delPos(params) {
      data.posList = null
      return this.performRequest('delPos', params)
    }
    // 获取岗位列表
    async getPosList() {
      try {
        const res = await this.performRequest('posList')
        return res
      } catch (e) {
        throw e.message
      }
    }

    // 查看岗位人员
    async roleMembers(params) {
      return this.performRequest('roleMembers', params)
    }
    // 添加岗位
    async addRole(params) {
      data.posList = null
      return this.performRequest('addRole', params)
    }
    async modifyRoleName(params) {
      data.posList = null
      return this.performRequest('modifyRoleName', params)
    }
    // 删除岗位
    async delRole(params) {
      data.posList = null
      return this.performRequest('delRole', params)
    }
    // 获取岗位列表
    async getRoleList() {
      try {
        const res = await this.performRequest('roleList')
        return res
      } catch (e) {
        throw e.message
      }
    }

    // 获取今日打卡详情
    getTodayDakaDetail(token, ack) {
      if (WebSock.ws == null) return resetRouter()
      WebSock.ws.emit('todayDakaDetail', { token }, ack)
    }

    // 打卡
    daka(token, dakaType, longitude, latitude, address, ack) {
      if (WebSock.ws == null) return resetRouter()
      WebSock.ws.emit('daka', { token, dakaType, longitude, latitude, address }, ack)
    }

    // 获取考勤设置
    getKaoqinSetting(token, ack) {
      if (WebSock.ws == null) return resetRouter()
      WebSock.ws.emit('getKaoqinSetting', { token }, ack)
    }

    // 更新考勤设置
    updateKaoqinSetting(token, params, ack) {
      if (WebSock.ws == null) return resetRouter()
      WebSock.ws.emit('updateKaoqinSetting', { token, ...params }, ack)
    }

    // 请假申请
    async vacationApply(params) {
      return this.performRequest('vacationApply', params)
    }
    async vacationApplyRecordWeb(params) {
      return this.performRequest('vacationApplyRecordWeb', params)
    }
    async revertVacationApply(params) {
      return this.performRequest('revertVacationApply', params)
    }

    // 出差申请
    async chuchaiApply(params) {
      return this.performRequest('chuchaiApply', params)
    }
    async chuchaiApplyRecordWeb(params) {
      return this.performRequest('chuchaiApplyRecordWeb', params)
    }
    async revertChuchaiApply(params) {
      return this.performRequest('revertChuchaiApply', params)
    }

    // 加班申请
    async jiabanApply(params) {
      return this.performRequest('jiabanApply', params)
    }
    async jiabanApplyRecordWeb(params) {
      return this.performRequest('jiabanApplyRecordWeb', params)
    }
    async revertJiabanApply(params) {
      return this.performRequest('revertJiabanApply', params)
    }

    // 获取未完成的任务数量
    async getUnfinishedTaskCnt() {
      return this.performRequest('getUnfinishedTaskCnt')
    }

    // 获取任务列表
    getTaskListWeb(params) {
      return this.performRequest('getTaskListWeb', params)
    }

    getNotificationListWeb(params) {
      return this.performRequest('getNotificationListWeb', params)
    }

    // 同意任务
    agreeTask(params) {
      return this.performRequest('agreeTask', params)
    }

    // 承办确认任务
    confirmTask(params) {
      return this.performRequest('confirmTask', params)
    }

    // 拒绝任务
    rejectTask(params) {
      return this.performRequest('rejectTask', params)
    }

    // 获取未读通知的数量
    async getUnreadNotificationCnt() {
      return this.performRequest('getUnreadNotificationCnt')
    }

    // 获取通知列表
    async getNotificationList(params) {
      return this.performRequest('getNotificationList', params)
    }

    // 阅读通知
    async readNotification(params) {
      return this.performRequest('readNotification', params)
    }

    // 获取通知信息
    async getNotificationInfo(params) {
      return this.performRequest('getNotificationInfo', params)
    }

    // 入职申请
    async entryApply(params) {
      return this.performRequest('entryApply', params)
    }
    async entryApplyRecordWeb(params) {
      return this.performRequest('entryApplyRecordWeb', params)
    }
    async revertEntryApply(params) {
      return this.performRequest('revertEntryApply', params)
    }

    // 转正申请
    async zhuanzhengApply(params) {
      return this.performRequest('zhuanzhengApply', params)
    }
    async zhuanzhengApplyRecordWeb(params) {
      return this.performRequest('zhuanzhengApplyRecordWeb', params)
    }
    async revertZhuanzhengApply(params) {
      return this.performRequest('revertZhuanzhengApply', params)
    }

    // 离职申请申请
    async departureApply(params) {
      return this.performRequest('departureApply', params)
    }
    async departureApplyRecordWeb(params) {
      return this.performRequest('departureApplyRecordWeb', params)
    }
    async revertDepartureApply(params) {
      return this.performRequest('revertDepartureApply', params)
    }

    // 督办单申请
    async dubandanApply(params) {
      return this.performRequest('dubandanApply', params)
    }
    async dubandanApplyRecordWeb(params) {
      return this.performRequest('dubandanApplyRecordWeb', params)
    }
    async revertDubandanApply(params) {
      return this.performRequest('revertDubandanApply', params)
    }

    // 会议室申请
    async meetingRoomApply(params) {
      return this.performRequest('meetingRoomApply', params)
    }
    async meetingRoomApplyRecordWeb(params) {
      return this.performRequest('meetingRoomApplyRecordWeb', params)
    }
    async revertMeetingRoomApply(params) {
      return this.performRequest('revertMeetingRoomApply', params)
    }

    // 接待申请
    async jiedaiApply(params) {
      return this.performRequest('jiedaiApply', params)
    }
    async jiedaiApplyRecordWeb(params) {
      return this.performRequest('jiedaiApplyRecordWeb', params)
    }
    async revertJiedaiApply(params) {
      return this.performRequest('revertJiedaiApply', params)
    }

    // 加油申请
    async jiayouApply(params) {
      return this.performRequest('jiayouApply', params)
    }
    async jiayouApplyRecordWeb(params) {
      return this.performRequest('jiayouApplyRecordWeb', params)
    }
    async revertJiayouApply(params) {
      return this.performRequest('revertJiayouApply', params)
    }

    // 用车申请
    async yongcheApply(params) {
      return this.performRequest('yongcheApply', params)
    }
    async yongcheApplyRecordWeb(params) {
      return this.performRequest('yongcheApplyRecordWeb', params)
    }
    async revertYongcheApply(params) {
      return this.performRequest('revertYongcheApply', params)
    }

    // 用印申请
    async yongyinApply(params) {
      return this.performRequest('yongyinApply', params)
    }
    async yongyinApplyRecordWeb(params) {
      return this.performRequest('yongyinApplyRecordWeb', params)
    }
    async revertYongyinApply(params) {
      return this.performRequest('revertYongyinApply', params)
    }

    // 发起会议
    async newMeeting(params) {
      return this.performRequest('newMeeting', params)
    }

    // 采购申请
    async caigouApply(params) {
      return this.performRequest('caigouApply', params)
    }
    async caigouApplyRecordWeb(params) {
      return this.performRequest('caigouApplyRecordWeb', params)
    }
    revertCaigouApply(params) {
      return this.performRequest('revertCaigouApply', params)
    }

    // 物资领用
    async wuzilingyong(params) {
      return this.performRequest('wuzilingyong', params)
    }
    async wuzilingyongRecordWeb(params) {
      return this.performRequest('wuzilingyongRecordWeb', params)
    }
    async revertWuzilingyong(params) {
      return this.performRequest('revertWuzilingyong', params)
    }

    // 合同审批
    async hetongShenpi(params) {
      return this.performRequest('hetongShenpi', params)
    }
    async hetongShenpiRecordWeb(params) {
      return this.performRequest('hetongShenpiRecordWeb', params)
    }
    async revertHetongShenpi(params) {
      return this.performRequest('revertHetongShenpi', params)
    }

    // 招标审核
    async zhaobiaoShenhe(params) {
      return this.performRequest('zhaobiaoShenhe', params)
    }
    async zhaobiaoShenheRecordWeb(params) {
      return this.performRequest('zhaobiaoShenheRecordWeb', params)
    }
    async revertZhaobiaoShenhe(params) {
      return this.performRequest('revertZhaobiaoShenhe', params)
    }

    // 传阅文件
    async chuanyueWenjian(params) {
      return this.performRequest('chuanyueWenjian', params)
    }
    async chuanyueWenjianRecordWeb(params) {
      return this.performRequest('chuanyueWenjianRecordWeb', params)
    }
    async revertChuanyueWenjian(params) {
      return this.performRequest('revertChuanyueWenjian', params)
    }

    // 公文流转
    async gongwenLiuzhuan(params) {
      return this.performRequest('gongwenLiuzhuan', params)
    }
    async gongwenLiuzhuanRecordWeb(params) {
      return this.performRequest('gongwenLiuzhuanRecordWeb', params)
    }
    async revertGongwenLiuzhuan(params) {
      return this.performRequest('revertGongwenLiuzhuan', params)
    }

    // 内部发文
    async neibuFawen(params) {
      return this.performRequest('neibuFawen', params)
    }
    async neibuFawenRecordWeb(params) {
      return this.performRequest('neibuFawenRecordWeb', params)
    }
    async revertNeibuFawen(params) {
      return this.performRequest('revertNeibuFawen', params)
    }

    // 公文信息
    async getGongwenInfo(params) {
      return this.performRequest('getGongwenInfo', params)
    }

    // 获取公文收藏列表
    async getGongwenShoucangList(params) {
      return this.performRequest('getGongwenShoucangList', params)
    }

    // 下载工资模板文件
    async gongziTemplateDownloadUrl(params) {
      return this.performRequest('gongziTemplateDownloadUrl', params)
    }

    async gongziRecordWeb(params) {
      return this.performRequest('gongziRecordWeb', params)
    }

    // 新建工资上传
    async newGongziUpload(params) {
      return this.performRequest('newGongziUpload', params)
    }

    // 工资上传记录
    async gongziUploadRecord(params) {
      return this.performRequest('gongziUploadRecord', params)
    }

    // 节假日配置
    async getJiejieriConfig(params) {
      return this.performRequest('getJiejieriConfig', params)
    }
    async updateJiejiariConfig(params) {
      return this.performRequest('updateJiejiariConfig', params)
    }

    // 排班
    async getXiuxiDayList(params) {
      return this.performRequest('getXiuxiDayList', params)
    }
    async addPaiban(params) {
      return this.performRequest('addPaiban', params)
    }

    // 请假详情
    async vacationApplyDetail(params) {
      return this.performRequest('vacationApplyDetail', params)
    }

    async chuchaiApplyDetail(params) {
      return this.performRequest('chuchaiApplyDetail', params)
    }

    async jiabanApplyDetail(params) {
      return this.performRequest('jiabanApplyDetail', params)
    }

    async entryApplyDetail(params) {
      return this.performRequest('entryApplyDetail', params)
    }

    async zhuanzhengApplyDetail(params) {
      return this.performRequest('zhuanzhengApplyDetail', params)
    }

    async departureApplyDetail(params) {
      return this.performRequest('departureApplyDetail', params)
    }

    async dubandanApplyDetail(params) {
      return this.performRequest('dubandanApplyDetail', params)
    }

    async meetingRoomApplyDetail(params) {
      return this.performRequest('meetingRoomApplyDetail', params)
    }

    async jiedaiApplyDetail(params) {
      return this.performRequest('jiedaiApplyDetail', params)
    }

    async jiayouApplyDetail(params) {
      return this.performRequest('jiayouApplyDetail', params)
    }

    async yongcheApplyDetail(params) {
      return this.performRequest('yongcheApplyDetail', params)
    }

    async yongyinApplyDetail(params) {
      return this.performRequest('yongyinApplyDetail', params)
    }

    async caigouApplyDetail(params) {
      return this.performRequest('caigouApplyDetail', params)
    }

    async wuzilingyongDetail(params) {
      return this.performRequest('wuzilingyongDetail', params)
    }

    async hetongShenpiDetail(params) {
      return this.performRequest('hetongShenpiDetail', params)
    }

    async zhaobiaoShenheDetail(params) {
      return this.performRequest('zhaobiaoShenheDetail', params)
    }

    async chuanyueWenjianDetail(params) {
      return this.performRequest('chuanyueWenjianDetail', params)
    }

    async gongwenLiuzhuanDetail(params) {
      return this.performRequest('gongwenLiuzhuanDetail', params)
    }

    async bukaApplyDetail(params) {
      return this.performRequest('bukaApplyDetail', params)
    }

    async huiyiTongzhiDetail(params) {
      return this.performRequest('huiyiTongzhiDetail', params)
    }

    async huiyiTongzhiRecordWeb(params) {
      return this.performRequest('huiyiTongzhiRecordWeb', params)
    }

    async newHuiyiTongzhi(params) {
      return this.performRequest('newHuiyiTongzhi', params)
    }

    async newGongzuoTongzhi(params) {
      return this.performRequest('newGongzuoTongzhi', params)
    }

    async gongzuoTongzhiDetail(params) {
      return this.performRequest('gongzuoTongzhiDetail', params)
    }

    async gongzuoTongzhiRecordWeb(params) {
      return this.performRequest('gongzuoTongzhiRecordWeb', params)
    }

    async paibanDetail(params) {
      return this.performRequest('paibanDetail', params)
    }

    async neibuFawenDetail(params) {
      return this.performRequest('neibuFawenDetail', params)
    }

    // 车牌
    async chepaiList(params) {
      return this.performRequest('chepaiList', params)
    }
    async deleteChepai(params) {
      return this.performRequest('deleteChepai', params)
    }
    async addChepai(params) {
      return this.performRequest('addChepai', params)
    }

    // 印章
    async yinzhangList(params) {
      return this.performRequest('yinzhangList', params)
    }
    async deleteYinzhang(params) {
      return this.performRequest('deleteYinzhang', params)
    }
    async addYinzhang(params) {
      return this.performRequest('addYinzhang', params)
    }

    // 会议室
    async huiyishiList(params) {
      return this.performRequest('huiyishiList', params)
    }
    async deleteHuiyishi(params) {
      return this.performRequest('deleteHuiyishi', params)
    }
    async addHuiyishi(params) {
      return this.performRequest('addHuiyishi', params)
    }

    // 请假
    async qingjiaList(params) {
      return this.performRequest('qingjiaList', params)
    }
    async deleteQingjia(params) {
      return this.performRequest('deleteQingjia', params)
    }
    async addQingjia(params) {
      return this.performRequest('addQingjia', params)
    }

    getUserInfoByUid(params) {
      return this.performRequest('getUserInfoByUid', params)
    }

    // 收藏公文
    shoucangGongwen(params) {
      return this.performRequest('shoucangGongwen', params)
    }

    cancelShoucang(params) {
      return this.performRequest('cancelShoucang', params)
    }

    gongwenShoucangListWeb(params) {
      return this.performRequest('gongwenShoucangListWeb', params)
    }

    gongwenHistoryListWeb(params) {
      return this.performRequest('getGongwenHistoryListWeb', params)
    }

    getEventConfig(params) {
      return this.performRequest('getEventConfig', params)
    }

    getRootConfig(params) {
      return this.performRequest('getRootConfig', params)
    }

    modifyDepartment(params) {
      return this.performRequest('modifyDepartment', params)
    }

    getLingdao(params) {
      return this.performRequest('getLingdao', params)
    }

    getDepartmentLingdao(params) {
      return this.performRequest('getDepartmentLingdao', params)
    }

    getAuditors(params) {
      return this.performRequest('getAuditors', params)
    }

    saveAuditStep(params) {
      return this.performRequest('saveAuditStep', params)
    }

    saveChengbanStep(params) {
      return this.performRequest('saveChengbanStep', params)
    }

    getUserPermissionsWeb(params) {
      return this.performRequest('getUserPermissionsWeb', params)
    }

    getAllUsers(params) {
      return this.performRequest('getAllUsers', params)
    }

    getPermissionsUsers(params) {
      return this.performRequest('getPermissionsUsers', params)
    }

    setPermissionUsers(params) {
      return this.performRequest('setPermissionUsers', params)
    }

    getUserGroupList(params) {
      return this.performRequest('getUserGroupList', params)
    }
    addUserGroup(params) {
      return this.performRequest('addUserGroup', params)
    }
    delUserGroup(params) {
      return this.performRequest('delUserGroup', params)
    }
    modifyUserGroup(params) {
      return this.performRequest('modifyUserGroup', params)
    }

    printPdf(params) {
      return this.performRequest('printPdf', params)
    }

    getPaibanSetting(params) {
      return this.performRequest('getPaibanSetting', params)
    }
    updatePaibanSetting(params) {
      return this.performRequest('updatePaibanSetting', params)
    }
    autoPaiban(params) {
      return this.performRequest('autoPaiban', params)
    }

    getShangbanDetail(params) {
      return this.performRequest('getShangbanDetail', params)
    }

    cuiban(params) {
      return this.performRequest('cuiban', params)
    }

    getTaskListWithStatusWeb(params) {
      return this.performRequest('getTaskListWithStatusWeb', params)
    }

    getNotificationListWithStatusWeb(params) {
      return this.performRequest('getNotificationListWithStatusWeb', params)
    }

    // 获取日程
    getSchedule(params) {
      return this.performRequest('getSchedule', params)
    }
    // 文件标签 列表
    fileTagList() {
      return this.performRequest('fileTagList')
    }

    /**
     * 添加文件标签
     * @param {*} params 传入参数  {name：''}
     * @returns
     */
    fileTagAdd(params) {
      return this.performRequest('fileTagAdd', params)
    }

    /**
     * 修改文件标签
     * @param {*} id
     * @param {*} name
     * @returns
     */
    fileTagModify(params) {
      return this.performRequest('fileTagModify', params)
    }
}

export const websock = new (WebSock)()
